package custom.base.log;

import android.content.Context;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import custom.base.utils.DelayUtil;
import custom.base.utils.store.ConstantsPreference;
import custom.base.utils.store.PreferencesManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;


/**
 * 全局日志管理
 * Created by cubebox on 2018/9/10.
 */
public class GlobeLog {

    private static GlobeLog intance = null;
    /**
     * 最大日志保存数量
     */
    private final int MAX_LOG_COUNT = 100;
    private DelayUtil delayUtil = null;

    private List<AppLog> logList = new ArrayList<>();

    public GlobeLog() {
        delayUtil = new DelayUtil();
    }

    public static GlobeLog getIntance() {
        synchronized (GlobeLog.class) {
            if (intance == null) {
                intance = new GlobeLog();
            }
            return intance;
        }
    }

    /**
     * 初始化日志调式工具，初始化的时候会自动装载一次日志记录的列表（从文件中）
     */
    public void initLogDebug(final Context context) {
//        Observable.create(new ObservableOnSubscribe<Object>() {
//            @Override
//            public void subscribe(@NonNull ObservableEmitter<Object> e) throws Exception {
//                List<AppLog> list = PreferencesManager.getInstance(context).getArray(ConstantsPreference.PRE_APP_LOG, AppLog.class);
//                if (list != null) {
//                    logList.addAll(list);
//                }
//            }
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<Object>() {
//                    @Override
//                    public void accept(@NonNull Object o) throws Exception {
//                        MLog.stressD("初始化日志工具完成");
//                    }
//                });

    }

    /**
     * 添加日志,只保留最近20条日志
     */
    public void addLog(final Context context, String label, String content) {
        synchronized (GlobeLog.class) {
            AppLog appLog = new AppLog();
            appLog.setLabel(label);
            appLog.setContent(content);
            appLog.setTime(System.currentTimeMillis());

            logList.add(0, appLog);
            if (delayUtil != null)
                delayUtil.cancle();
            delayUtil.delay(2000, new DelayUtil.OnDelayListener() {
                @Override
                public void onDelayFinish() {
                    //去除掉日志最大数量之外的所有日志
                    if (logList.size() >= MAX_LOG_COUNT) {
                        for (int i = MAX_LOG_COUNT; i < logList.size(); i++) {
                            logList.remove(i);
                        }
                    }
                }

                @Override
                public void onDealing() {

                }
            });
        }
//        if (delayUtil != null)
//            delayUtil.cancle();
        //为防止并发所以做一个延迟日志
//        delayUtil.delay(2000, new DelayUtil.OnDelayListener() {
//            @Override
//            public void onDelayFinish() {
//                Observable.create(new ObservableOnSubscribe<Object>() {
//                    @Override
//                    public void subscribe(@NonNull ObservableEmitter<Object> e) throws Exception {
//                        //去除掉日志最大数量之外的所有日志
//                        if (logList.size() >= MAX_LOG_COUNT) {
//                            for (int i = MAX_LOG_COUNT; i < logList.size(); i++) {
//                                logList.remove(i);
//                            }
//                        }
//                        PreferencesManager.getInstance(context).putString(ConstantsPreference.PRE_APP_LOG, new Gson().toJson(logList));
//                    }
//                }).subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Consumer<Object>() {
//                            @Override
//                            public void accept(@NonNull Object o) throws Exception {
//                                MLog.stressD("初始化日志工具完成");
//                            }
//                        });
//            }
//
//            @Override
//            public void onDealing() {
//
//            }
//        });
    }

    /**
     * 保存日志到本地
     */
    public void saveLogToLocal(final Context context) {
        synchronized (GlobeLog.class) {
            Observable.create(new ObservableOnSubscribe<Object>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<Object> e) throws Exception {
                    //去除掉日志最大数量之外的所有日志
                    if (logList.size() >= MAX_LOG_COUNT) {
                        for (int i = MAX_LOG_COUNT; i < logList.size(); i++) {
                            logList.remove(i);
                        }
                    }
                    PreferencesManager.getInstance(context).putString(ConstantsPreference.PRE_APP_LOG, new Gson().toJson(logList));
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(@NonNull Object o) throws Exception {
                            MLog.d("初始化日志工具完成");
                        }
                    });
        }

    }

    public List<AppLog> getLogList() {
        return logList;
    }

}
